package com.example.demoapp.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerBase;
import cn.hutool.http.server.HttpServerRequest;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demoapp.entity.Employee;
import com.example.demoapp.exception.BusinessException;
import com.example.demoapp.service.EmployeeService;
import jakarta.annotation.Resource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Calendar;
import java.util.Date;

public class TokenUtils {

    @Resource
    private static EmployeeService employeeService;

    //生成token
    public static String  createToken(String data,String sign){
        // 计算1天后的过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1); // 增加1天
        return JWT.create().withAudience(data)//将userID和角色等保存到token里，作为负载（一般用户信息都存在payload（负载里））
                .withExpiresAt(calendar.getTime())//1天后token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥，HMAC256算法加密
    }

    //获取当前登入的用户信息
    public static Employee getcurrentUser(){
        HttpServerRequest request = (HttpServerRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String  token = request.getHeader("token");

        String audience = JWT.decode(token).getAudience().get(0);
        String [] split = audience.split("-");
        //token负载的信息
        Integer userId = Integer.valueOf(split[0]);
        String role = split[1];

        //根据id去查询是否有这个账号
        Employee employee = employeeService.selecByid(userId);

        return employee;
    }
}
